<?php

class purse {
    public function scanCardcode($param){
        $id = $param->id;
        $userName = $param->message->fromUserName;
        $codeId = $param->codeId;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $cardModel = M("module_rechargecard");
        $cardRecordModel= M("module_recharge_record");
        $purseModel= M("module_user_purse");
        $purseBillModel= M("module_user_purse_bill");
        $code = M("qrcode");
        Session::switchCustomer($cid);
        $userModel = M("user_weixin_info");
        $materialModel = M("material");
        $time = time();
        $cardInfo = $cardModel->where("id=$id")->find();
        if($cardInfo['deleted']==1||$cardInfo['status']==0){
            //删除或停用
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的充值卡已经被删除或者停用。");
            return;
        }
        if($cardInfo['surplusNum']<=0){
            //领光了
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的充值卡已经被领光。");
            return;
        }
        if($cardInfo['isEffective']==1&&(strtotime($cardInfo['startTime'])>$time||strtotime($cardInfo['endTime'])<$time)){
            //没到领取时间或超过领取时间
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的充值卡不再领取时间范围内。");
            return;
        }
        $materialId = $cardInfo["newsId"];
        $userInfo =$userModel->where("openid='$userName'")->field("userId,nickname")->find();
        $userId = $userInfo['userId'];
        $cardModel->startTrans();
        $result = $cardModel->where("id=$id")->setDec("surplusNum");
        if($result){
            $data['cid']=$cid;
            $data['userId']=$userId;
            $data['rechargecardId']=$id;
            $data['money']=$cardInfo['money'];
            $data['createTime']=date("Y-m-d H:i:s");
            $result = $cardRecordModel->add($data);
            if($result){
                $purseInfo= $purseModel->where("cid=$cid and userId=$userId")->find();
                $data = null;
                if($purseInfo){
                    $data['totalRecharge']=$purseInfo['totalRecharge']+$cardInfo['money'];
                    $data['balance']=$purseInfo['balance']+$cardInfo['money'];
                    $data['updateTime']=date("Y-m-d H:i:s");
                    $result = $purseModel->where("id=".$purseInfo['id'])->save($data);
                }else{
                    $data['cid']=$cid;
                    $data['userId']=$userId;
                    $data['totalRecharge']=$cardInfo['money'];
                    $data['balance']=$cardInfo['money'];
                    $data['updateTime']=date("Y-m-d H:i:s");
                    $result = $purseModel->add($data);
                }
                if($result){
                    $data = null;
                    $data['cid']=$cid;
                    $data['userId']=$userId;
                    $data['module']='code';
                    $data['moduleId']=$codeId;
                    $data['description']="充值卡";
                    $data['money']=$cardInfo['money'];
                    $data['type']=0;
                    $data['createTime']=date("Y-m-d H:i:s");
                    $result = $purseBillModel->add($data);
                    if($result){
                        $code->where("id=$codeId")->setField("method","scanedCode");
                        $materialInfo = $materialModel->where("id=".$materialId)->find();
                        $xml = (string)$materialInfo["xml"];
                        $xml = str_replace("{{nickname}}",$userInfo['nickname'],$xml);
                        $xml = str_replace("{{price}}",$cardInfo['money'],$xml);
                        $xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
                        $item = $xml->Articles->item;
                        $articles=array();
                        foreach($item as $key=>$value){
                            $article=new stdClass();
                            $article->title = urlencode((string)$value->title);
                            $article->url = urlencode((string)$value->url);
                            $article->picurl = urlencode((string)$value->picUrl);
                            $article->description = urlencode((string)$value->description);
                            array_push($articles, $article);
                        }
                        $toUser = $userName;
                        WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
                        $cardModel->commit();
                        return;
                    }
                }
            }
        }

        $cardModel->rollback();
        return;
    }
    public function scanedCode($param){
//        \Log::write('lilei_purse::scanedCode_' . json_encode($param));
        $userName = $param->message->fromUserName;
        WeixinApi::sendServiceMsg($userName,"text","该二维码对应的充值卡经被领取过了，无法再次领取。");
    }
    public function index($token){
        $token = Module::callModule("personCenter",null,"verifyToken",$token);
        $cid = Session::$user['customerId'];
        $userId= Session::$user['userId'];
        Session::switchCustomer(0);
        $purseModel = M("module_user_purse");
        Session::switchCustomer($cid);
        $userModel = M('user');
        $result = $purseModel->where("userId = $userId and cid = $cid")->find();
        $result['mallHue']=Module::callModule("product",null,"getMallHue",null);
        $payPassword = $userModel->where("id = $userId")->getField('payPassword');
        (empty($payPassword)) ? $payPassword = 0 : $payPassword = 1;
        $result['payPassword'] = $payPassword;
        Output::instance()->module("purse","index")->object($result);
    }
    public function getBill(){
        Output::instance()->module("purse","billList")->object(null);
    }
    public function getBillList($start,$limit){
        $cid = Session::$user['customerId'];
        $userId= Session::$user['userId'];
        Session::switchCustomer(0);
        $purseBillModel = M("module_user_purse_bill");
        Session::switchCustomer($cid);
        $start = $start*$limit;
        $arr = $purseBillModel->where("userId=$userId")->limit($start,$limit)->order("createTime desc")->select();
        foreach($arr as $key=>$value){
            $update = date("Y-m-d",strtotime($value["createTime"]));
            $datatime=date('Y-m-d');
            $yesterday = date("Y-m-d",time()-24*60*60);
            if($update==$datatime){
                $arr[$key]["time1"] = "今天";
            }else if($update==$yesterday){
                $arr[$key]["time1"] = "昨天";
            }else{
                $arr[$key]["time1"] = date("m-d",strtotime($value["createTime"]));
            }
            $arr[$key]["time2"] = date("H:i",strtotime($value["createTime"]));
        }
        if($arr){
            $count = $purseBillModel->where("userId=$userId")->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }

    /**验证旧密码，修改支付密码或支付时时调用
     * @param $oldPassword 旧密码
     */
    public function contrastPayPassword($oldPassword, $orderId = '')
    {
        $cid = Session::$user['customerId'];
        $userId= Session::$user['userId'];
        Session::switchCustomer($cid);
        $user = M('user');

        $where['customerId'] = $cid;
        $where['id'] = $userId;
        $PayPassword = $user->where($where)->getField('payPassword');
        $md5OldPassword = md5($oldPassword);

        if ($oldPassword) {
            if ($PayPassword == $md5OldPassword) {
                $token = md5(time());
                $redis = new Redis();
                if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
                    && $redis->auth(C('REDIS_PASSWORD')) == TRUE
                    && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
                ) {
                    if (empty($orderId)) {
                        $redis->set('PayPasswordToken'.$userId, $token);
                        $redis->expire('PayPasswordToken'.$userId, 60);
                    } else {
                        $redis->set('PayPasswordToken'.$orderId, $token);
                        $redis->expire('PayPasswordToken'.$orderId, 1800);
                    }
                }
                Output::instance()->object([
                    'code' => 0,
                    'msg' => '验证成功',
                    'token' => $token
                ]);
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '验证失败'
                ]);
            }
        } else {
            Output::instance()->module("purse","checkPaypassword")->object([]);
        }


    }

    /**设置支付密码
     * @param $password 密码
     * @param string $token 令牌
     */
    public function setPayPassword($password, $tokens = '')
    {
        if ($password) {
            $cid = Session::$user['customerId'];
            $userId= Session::$user['userId'];
            Session::switchCustomer($cid);
            $user = M('user');

            $data['payPassword'] = md5($password);
            $where['customerId'] = $cid;
            $where['id'] = $userId;
            $oldPayPassword = $user->where($where)->getField('payPassword');

            if (empty($oldPayPassword)) {//初次设置
                $res = $user->where($where)->save($data);
            } else {//修改
                $redis = new Redis();
                if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
                    && $redis->auth(C('REDIS_PASSWORD')) == TRUE
                    && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
                ) {
                    $redisToken = $redis->get('PayPasswordToken'.$userId);
                }
                if ($tokens == $redisToken) {
                    $res = $user->where($where)->save($data);
                } else {
                    Output::instance()->object([
                        'code' => 2,
                        'msg' => 'token验证错误'
                    ]);
                    return;
                }
            }

            if (is_numeric($res)) {
                Output::instance()->object([
                    'code' => 0,
                    'msg' => '设置成功'
                ]);
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '设置失败'
                ]);
            }
        } else {
            Output::instance()->module("purse","setPaypassword")->object([]);
        }

    }

    /**忘记密码获取验证码
     * @param $phone 手机号
     */
    public function forgetPayPassword($phone)
    {
        $cid = Session::$user['customerId'];
        $userId= Session::$user['userId'];
        Session::switchCustomer($cid);
        $user = M('user');

        $phone1 = $user->where("id = $userId")->getField('phone');
        if ($phone == $phone1) {
            $module = 'phone';
            $method = 'sendPhoneCode';
            $params = new stdClass();
            $params->phone = $phone;
            $params->module = 'newPurse';
            Module::callModule($module, NULL, $method, $params);
        } else {
            Output::instance()->object([
                'code' => 2,
                'msg' => '手机号不正确'
            ]);
        }
    }

    /**验证手机验证码
     * @param $phone 手机号
     * @param $code 验证码
     */
    public function contrastPhoneCode($phone, $code)
    {
        if ($phone && $code) {
            $userId = $userId= Session::$user['userId'];
            $module = 'phone';
            $method = 'verifyPhoneCode';
            $params = new stdClass();
            $params->phone = $phone;
            $params->code = $code;
            $result = Module::callModule($module, NULL, $method, $params);

            if ($result) {
                $token = md5(time());
                $redis = new Redis();
                if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
                    && $redis->auth(C('REDIS_PASSWORD')) == TRUE
                    && $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
                ) {
                    $redis->set('PayPasswordToken'.$userId, $token);
                    $redis->expire('PayPasswordToken'.$userId, 60);
                }
                Output::instance()->object([
                    'code' => 0,
                    'msg' => '验证成功',
                    'token' =>$token
                ]);
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '验证失败'
                ]);
            }
        } else {
            Output::instance()->module("purse","forgotPaypassword")->object([]);
        }

    }
}